package com.splant.android.smart.UILevel.Community;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;
import com.splant.android.smart.CommunicationLevel.sPlantAsyncHttpClient;
import com.splant.android.R;
import com.splant.android.smart.CommunicationLevel.sPlantJsonHttpResponseHandler;
import com.splant.android.smart.Global;
import com.splant.android.smart.ModelLevel.User;
import com.splant.android.smart.ModelLevel.sPlantRequestParams;
import com.splant.android.smart.SystemDefinedLevel.DeciveManager.DeviveMessages;
import com.splant.android.smart.SystemDefinedLevel.DeciveManager.ScreenInfo;
import com.splant.android.smart.SystemDefinedLevel.GenericControls.Dialog.LoadingDialog;
import com.splant.android.smart.SystemDefinedLevel.Utils.System_Util;

import org.apache.http.Header;
import org.json.JSONObject;

import de.hdodenhof.circleimageview.CircleImageView;

public class Garden_Login_Activity extends Garden_Base_Activity implements View.OnClickListener {

    private sPlantAsyncHttpClient sPlantClient;
    private CircleImageView cImg_logo;
    private EditText edt_userName;
    private EditText edt_psw;
    private CheckBox chk_rememberPsw;
    private Button btn_login;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.garden_login_activity);

        cImg_logo = (CircleImageView) findViewById(R.id.cImg_logo);
        edt_userName = (EditText) findViewById(R.id.edt_userName);
        edt_psw = (EditText) findViewById(R.id.edt_psw);
        btn_login = (Button) findViewById(R.id.btn_login);
        chk_rememberPsw= (CheckBox) findViewById(R.id.chk_rememberPsw);

        init();

        btn_login.setOnClickListener(this);
        chk_rememberPsw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                SharedPreferences.Editor editor=preferences.edit();
                editor.putBoolean("isRememberPsw",isChecked);
                editor.commit();

            }
        });
    }
    private SharedPreferences preferences;
    private void init()
    {
        sPlantClient = sPlantAsyncHttpClient.getInstance();

        Global.screenInfo= DeviveMessages.getScreenInfo(this,getWindowManager());

        loadingDialog = LoadingDialog.createDialog(this);
        preferences = getSharedPreferences("User", MODE_PRIVATE);
        String userName=preferences.getString("userName","");
        String password=preferences.getString("password","");
        boolean isRememberPsw=preferences.getBoolean("isRememberPsw",true);
        String logoUrl=preferences.getString("logoUrl","");

        edt_userName.setText(userName);
        chk_rememberPsw.setChecked(isRememberPsw);

        if (isRememberPsw)
            edt_psw.setText(password);

        if (logoUrl.equals("")==false)
        {
            Glide.with(this)
                    .load(logoUrl)
                    .dontAnimate()
                    .placeholder(R.mipmap.gaiaa_splant_ic_logo)
                    .into(cImg_logo);
        }

    }

    private LoadingDialog loadingDialog;
    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.btn_login:
                login();
                break;

        }
    }

    private void login() {

        final String userName = edt_userName.getText().toString();
        final String password = edt_psw.getText().toString();

        if (userName.equals("")) {
            Toast.makeText(this, "用户名为空，请输入", Toast.LENGTH_SHORT).show();

            System_Util.setEditGetFocus(edt_userName);
        } else if (password.equals("")) {
            Toast.makeText(this, "密码为空，请输入", Toast.LENGTH_SHORT).show();

            System_Util.setEditGetFocus(edt_psw);

        } else {

            if (loadingDialog.isShowing()==false)
                loadingDialog.show();

            sPlantRequestParams params=new sPlantRequestParams();
            params.putParams("username", userName);
            params.putParams("passWord", password);

            sPlantClient.post(this,sPlantAsyncHttpClient.USER_LOGIN,params,new sPlantJsonHttpResponseHandler() {
                        @Override
                        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                            try
                            {
                                loadingDialog.dismiss();

                                if (response.getInt("succeed") == 1) {

                                    JSONObject userInfoJObj = response.getJSONObject("user");

                                    Gson gson = new Gson();
                                    Global.user = gson.fromJson(userInfoJObj.toString(), User.class);

                                    SharedPreferences preferences = getSharedPreferences("User", MODE_PRIVATE);
                                    SharedPreferences.Editor editor = preferences.edit();

                                    editor.putString("logoUrl",Global.user.getLogoUrl());

                                    editor.putString("userName",userName);

                                    if (chk_rememberPsw.isChecked())
                                        editor.putString("password",password);

                                    editor.apply();

                                    Intent intent=new Intent(Garden_Login_Activity.this,Garden_Main_Activity.class);
                                    startActivity(intent);

                                    finish();
                                }
                                else if (response.getInt("succeed") == 0)
                                {
                                    Toast.makeText(Garden_Login_Activity.this,"用户名或者密码错误，请重新输入", Toast.LENGTH_SHORT).show();
                                }

                            } catch (Exception e) {

                            }
                        }
                        @Override
                        public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {

                            loadingDialog.dismiss();
                            Toast.makeText(Garden_Login_Activity.this,getString(R.string.system_request_error), Toast.LENGTH_SHORT).show();

                        }
                    }
            );

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }


}
